package com.youdoneed.friends.friends;

import com.youdoneed.base.application.ResultMessage;
import com.youdoneed.base.common.JWTUtils;
import com.youdoneed.friends.coolface.HasCheckCoolFaceService;
import com.youdoneed.friends.model.Contact;
import com.youdoneed.friends.model.RemoveRecommendFriends;
import com.youdoneed.friends.vo.*;
import com.youdoneed.user.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 通讯录好友模块请求控制器
 *
 * @author shum
 * @date 2017.6.12
 */
@RestController
@RequestMapping(value = "/friends")
@Api(value = "通讯录好友模块请求控制器", description = "通讯录好友模块请求控制器")
public class FriendsController {

    private static final Logger logger = LoggerFactory.getLogger(FriendsController.class);
    @Autowired
    FriendsService friendsService;

    @Autowired
    FriendsConfirmService friendsConfirmService;

    @Autowired
    RemoveRecommendFriendsService removeRecommendFriendsService;

    @Autowired
    HasCheckCoolFaceService hasCheckCoolFaceService;

    @RequestMapping(value = "/getFriendsCount", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取好友数", value = "获取好友数")
    public ResultMessage<Long> getFriendsCount(@RequestHeader("Authorization") String token){
        String userId = JWTUtils.getTokenUserId(token);
        Long count = friendsService.getFriendsCount(userId);
        return new ResultMessage().setData(count).toSuccess("获取好友数成功");
    }

    @RequestMapping(value = "/saveFriends", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "后台直接保存好友", value = "后台直接保存好友")
    public ResultMessage saveFriends(
            @ApiParam("好友id") @RequestParam String friendId,
            @RequestHeader("Authorization") String token) {
        logger.info("后台直接保存好友");
        String userId = JWTUtils.getTokenUserId(token);
        friendsService.saveFriends(userId, friendId);
        return new ResultMessage();
    }

    @RequestMapping(value = "/saveFriendsConfirm", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "后台保存好友请求", value = "后台保存好友请求")
    public ResultMessage saveFriendsConfirm(
            @ApiParam("好友id") @RequestBody List<String> friendIdList,
            @ApiParam("提示内容") @RequestParam(required = false) String notice,
            @RequestHeader("Authorization") String token) {
        logger.info("后台保存好友请求");
        String userId = JWTUtils.getTokenUserId(token);
        friendsConfirmService.saveConfirm(userId, notice, friendIdList);
        return new ResultMessage();
    }

    @RequestMapping(value = "/saveCoolfaceConfirm", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "后台保存coolface加好友请求", value = "后台保存coolface加好友请求")
    public ResultMessage saveCoolfaceConfirm(
            @ApiParam("好友id") @RequestParam String friendId,
            @ApiParam("searchId") @RequestParam String searchId,
            @RequestHeader("Authorization") String token) {
        logger.info("后台保存好友请求");
        String userId = JWTUtils.getTokenUserId(token);
        friendsConfirmService.saveCoolfaceConfirm(userId, friendId, searchId);
        return new ResultMessage("加好友请求发送成功");
    }

    @RequestMapping(value = "/getCoolfaceRequest", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取我被coolface加好友的请求", value = "获取我被coolface加好友的请求")
    public ResultMessage getCoolfaceRequest(@RequestHeader("Authorization") String token) {
        logger.info("获取我被coolface加好友的请求");
        String userId = JWTUtils.getTokenUserId(token);
        List<CoolfaceRequestVo> listCoolfaceRequestVo = friendsConfirmService.getCoolfaceRequest(userId);
        return new ResultMessage<>(listCoolfaceRequestVo);
    }

    /**
     * 获取首页头部coolface消息
     * @param token
     * @param isFirstLogin
     * @return
     * @author lid
     * @date 2017.11.14
     */
    @RequestMapping(value = "/getIndexCoolfaceInfo", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取首页头部coolface消息", value = "获取首页头部coolface消息")
    public ResultMessage<List<CoolfaceInfoVo>> getIndexCoolfaceInfo(@RequestHeader("Authorization") String token,
                                              @ApiParam("是否第一次登陆，（1是第一次登陆，0不是第一次登陆,2获取测试数据）")
                                              @RequestParam Integer isFirstLogin,
                                              @RequestParam double userLatitude,
                                              @RequestParam double userLongitud,
                                              @RequestParam Integer distance){
        logger.info("获取首页头部coolface消息");
        String userId = JWTUtils.getTokenUserId(token);
        List<CoolfaceInfoVo> listCoolfaceInfo = new ArrayList<>();
        listCoolfaceInfo = friendsService.getIndexCoolfaceInfo(userId,
                 isFirstLogin, userLatitude, userLongitud, distance);
        logger.info("listCoolfaceInfo.size():"+listCoolfaceInfo.size());
        return new ResultMessage<>(listCoolfaceInfo);
    }

    /**
     * 移除coolfaceinfo
     * "coolfaceMe"类型的直接在APP端删除，不需要掉后台接口，因为只有在用户第一次登陆的时候才会出现
     * "coolfacedUserRegister"  传 CoolfaceNotice 的noticeId值
     * "coolfaceMeApplyToBeFriend" 传FriendsConfirm 的confirmId值
     * "recommandUser"类型的直接在APP端删除，不需要掉后台接口，因为只有在用户第一次登陆的时候才会出现
     * @return
     */
    /*@RequestMapping(value = "/removeCoolfaceInfo", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "移除首页头部coolface消息" +
            "\"coolfaceMe\"和\"recommandUser\"类型的直接在APP端删除，" +
            "\"coolfacedUserRegister\"  传 CoolfaceNotice 的noticeId值，" +
            "\"coolfaceMeApplyToBeFriend\" 传FriendsConfirm 的confirmId值", value = "移除首页头部coolface消息")
    public ResultMessage<?> removeCoolfaceInfo(@RequestParam String infoType, @RequestParam String id){
        friendsService.removeCoolfaceInfo(infoType,id);
        return new ResultMessage<>("移除首页头部coolface消息成功!");
    }*/


    @RequestMapping(value = "/updateFriendsConfirm", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "后台更新好友请求", value = "后台更新好友请求")
    public ResultMessage updateFriendsConfirm(
            @ApiParam("请求id") @RequestParam String confirmId,
            @ApiParam("提示内容") @RequestParam(required = false) String notice,
            @ApiParam("处理标志（0：未处理；1：已处理且接受；2：已处理且拒绝）")
            @RequestParam Integer handleFlag) {
        logger.info("后台更新好友请求");
        friendsConfirmService.updateConfirm(confirmId, notice, handleFlag);
        return new ResultMessage();
    }


    @RequestMapping(value = "/autoAddFriends", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "后台自动加好友", value = "后台自动加好友")
    public ResultMessage<Long> autoAddFriends(@RequestHeader("Authorization") String token) {
        logger.info("后台自动加好友");
        String userId = JWTUtils.getTokenUserId(token);
        return new ResultMessage<>(friendsConfirmService.autoUpdate(userId));
    }

    @RequestMapping(value = "/deleteFriendsConfirm", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "后台删除好友请求记录", value = "后台删除好友请求记录")
    public ResultMessage deleteFriendsConfirm(
            @ApiParam("好友id") @RequestParam String friendId,
            @RequestHeader("Authorization") String token) {
        logger.info("后台删除好友请求记录");
        String userId = JWTUtils.getTokenUserId(token);
        // 这里删除的是别人加我为好友的请求
        friendsConfirmService.deleteConfirm(friendId, userId);
        return new ResultMessage().setMessage("后台删除好友请求记录成功");
    }

    @RequestMapping(value = "/findFriendsConfirm", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "后台查询好友请求", value = "后台查询好友请求")
    public ResultMessage<List<FindFriendsConfirmVO>> findFriendsConfirmList(
            @ApiParam("处理标志（0：未处理；1：已处理且接受；2：已处理且拒绝）")
            @RequestParam(required = false) Integer handleFlag,
            @RequestHeader("Authorization") String token) {
        logger.info("后台查询好友请求");
        String userId = JWTUtils.getTokenUserId(token);
        return new ResultMessage<>(friendsConfirmService.findFriendsConfirm(userId, handleFlag));
    }

    @RequestMapping(value = "/findFriendsList", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "后台查询我的好友列表", value = "后台查询我的好友列表")
    public ResultMessage<List<FindFriendsVO>> findFriendsList(
            @ApiParam("好友用户id") @RequestParam(required = false) String friendId,
            @RequestHeader("Authorization") String token) {
        logger.info("后台查询我的好友列表");
        String userId = JWTUtils.getTokenUserId(token);
        return new ResultMessage<>(friendsService.findFriendsList(userId, friendId));
    }

    @RequestMapping(value = "/findFriends", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "查询我的好友（news专用）", value = "查询我的好友（news专用）")
    public ResultMessage<List<User>> findFriends(@RequestHeader("Authorization") String token) {
        logger.info("查询我的好友（news专用）");
        String userId = JWTUtils.getTokenUserId(token);
        return new ResultMessage<>(friendsService.findFriends(userId));
    }

    @RequestMapping(value = "/findFriendIds", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "查询我的好友的id", value = "查询我的好友的id")
    public ResultMessage<UserRelationsVO> findFriendIds(
            @RequestParam Integer type,
            @RequestHeader("Authorization") String token) {
        logger.info("查询我的好友的id");
        String userId = JWTUtils.getTokenUserId(token);
        UserRelationsVO userRelationsVO = new UserRelationsVO();
        // type:1、查找好友id;2、查找黑名单id;3、两者都要;4、全部返回
        if (type == 1) {
            List<String> friendIds = friendsService.findFriendIds(userId, 1);
            userRelationsVO.setFriendIds(friendIds);
        } else if (type == 2) {
            List<String> blackFriendIds = friendsService.findFriendIds(userId, 0);
            userRelationsVO.setBlackIds(blackFriendIds);
        } else if (type == 3) {
            List<String> friendIds = friendsService.findFriendIds(userId, 1);
            List<String> blackFriendIds = friendsService.findFriendIds(userId, 0);
            userRelationsVO.setFriendIds(friendIds);
            userRelationsVO.setBlackIds(blackFriendIds);
        } else {
            List<String> friendIds = friendsService.findFriendIds(userId, 1);
            List<String> blackFriendIds = friendsService.findFriendIds(userId, 0);
            List<String> hasConfirmIds = friendsConfirmService.findMyConfirm(userId);
            userRelationsVO.setFriendIds(friendIds);
            userRelationsVO.setBlackIds(blackFriendIds);
            userRelationsVO.setHasConfirmUserIds(hasConfirmIds);
        }
        return new ResultMessage<>(userRelationsVO);
    }

    @RequestMapping(value = "/updateFriends", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "后台更新好友", value = "后台更新好友")
    public ResultMessage<String> updateFriends(
            @ApiParam("好友id") @RequestParam String friendId,
            @ApiParam("是否拉黑（0：加入黑名单；1：未加入）") @RequestParam(required = false) Integer blBlack,
            @ApiParam("是否删除（0：已删除；1：未删除）") @RequestParam(required = false) Integer blDelete,
            @RequestHeader("Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        friendsService.updateFriends(userId, friendId, blBlack, blDelete);
        return new ResultMessage<String>().toSuccess("后台更新好友成功");
    }

    @RequestMapping(value = "/getAddressByPhone", method = {RequestMethod.POST})
    @ApiOperation(notes = "手机通讯录好友", value = "手机通讯录好友")
    public ResultMessage<PhoneAddressVO> getAddressByPhone(
            @RequestBody List<User> userList,
            @RequestHeader("Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        return new ResultMessage<>(friendsService.findAddressByPhone(userId, userList));
    }

    /**
     * 获取手机通讯录好友（不用传通讯录）
     * @param token
     * @return
     * @author lid
     * @date 2018.1.5
     */
    @RequestMapping(value = "/findPhoneFriendsByPhone", method = {RequestMethod.POST})
    @ApiOperation(notes = "手机通讯录好友（不用传通讯录）", value = "手机通讯录好友（不用传通讯录）")
    public ResultMessage<PhoneAddressVO> findPhoneFriendsByPhone(@RequestParam @ApiParam("每页多少行") Integer rows,
                                                                 @RequestParam @ApiParam("第几页，从第1页开始") Integer currentPage,
                                                                 @RequestHeader("Authorization") String token){
        String userId = JWTUtils.getTokenUserId(token);
        return new ResultMessage<>(friendsService.findPhoneFriendsByPhone(rows, currentPage, userId));
    }

    @RequestMapping(value = "/findCommonFriends", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "查询共同好友", value = "查询共同好友")
    public ResultMessage<List<FindMutualFriendsVO>> findCommonFriends(
            @ApiParam("好友id") @RequestParam String friendId,
            @RequestHeader("Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        return new ResultMessage<>(friendsService.findCommonFriends(userId, friendId));
    }

    @RequestMapping(value = "/findRecommendFriends", method = RequestMethod.POST)
    @ApiOperation(notes = "查询推荐好友（共同好友和通讯录好友）", value = "查询推荐好友（共同好友和通讯录好友）")
    public ResultMessage<RecommendsFriends> findRecommendFriends(
            @ApiParam("通讯录参数") @RequestBody(required = false)
                    RecommendFriendsParam recommendFriendsParam,
            @RequestHeader("Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        RecommendsFriends recommendsFriends;
        // 如果有好友ID则查该好友的好友、否则查所有好友的好友及通讯录好友
        if(StringUtils.hasText(recommendFriendsParam.getFriendId())){
            recommendsFriends = friendsService.findFriendsOfFiend(recommendFriendsParam,userId);
        }else{
            recommendsFriends = friendsService.findRecommendFriends(recommendFriendsParam,userId);
        }
        return new ResultMessage<>(recommendsFriends);
    }

    @RequestMapping(value = "/removeRecommendFriends", method = RequestMethod.POST)
    @ApiOperation(notes = "移除推荐好友", value = "移除推荐好友")
    public ResultMessage<String> removeRecommendFriends(
            @ApiParam("好友id") @RequestParam String friendId,
            @RequestHeader("Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        RemoveRecommendFriends record = new RemoveRecommendFriends();
        record.setUserId(userId);
        record.setFriendId(friendId);
        record.setCreateTime(new Date());
        removeRecommendFriendsService.saveRemoveRecommendFriends(record);
        return new ResultMessage<String>().toSuccess("移除推荐好友成功");
    }

    @RequestMapping(value = "/removeHasCheckCoolFace", method = RequestMethod.POST)
    @ApiOperation(notes = "移除已经查看过的coolface搜索过我", value = "移除已经查看过的coolface搜索过我")
    public ResultMessage<String> removeHasCheckCoolFace(
            @ApiParam("搜索id") @RequestParam String searchId,
            @RequestHeader("Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        hasCheckCoolFaceService.saveHasCheckCoolFace(userId, searchId);
        return new ResultMessage<String>().toSuccess("移除已经查看过的coolface搜索过我成功");
    }

    @RequestMapping(value = "/isFriendOrFocus", method = RequestMethod.POST)
    @ApiOperation(notes = "判断是否为好友是否关注", value = "判断是否为好友是否关注")
    public ResultMessage<FriendOrFocusVO> isFriendOrFocus(
            @ApiParam("好友id") @RequestParam String friendId,
            @RequestHeader("Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        return new ResultMessage<>(friendsService.isFriendOrFocus(userId, friendId));
    }

    @RequestMapping(value = "/isFriendOrNot", method = RequestMethod.POST)
    @ApiOperation(notes = "判断是否为好友关系（user项目用）", value = "判断是否为好友关系（user项目用）")
    public ResultMessage<List<String>> isFriendOrNot(
            @ApiParam("好友id") @RequestBody String[] friendIds,
            @RequestHeader("Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        return new ResultMessage<>(friendsService.isFriendOrNot(userId, friendIds));
    }

    @RequestMapping(value = "/updateContacts", method = RequestMethod.POST)
    @ApiOperation(notes = "更新用户手机通讯录", value = "更新用户手机通讯录")
    public ResultMessage<Long> updateContacts(
            @ApiParam("通讯录对象数组") @RequestBody Contact[] contacts,
            @RequestHeader("Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        return new ResultMessage<>(friendsService.updateContacts(userId, contacts));
    }

    @RequestMapping(value = "/getContacts", method = RequestMethod.POST)
    @ApiOperation(notes = "获取用户手机通讯录", value = "获取用户手机通讯录")
    public ResultMessage<List<Contact>> getContacts(
            @RequestHeader("Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        return new ResultMessage<>(friendsService.getContacts(userId));
    }

}
